package register

import (
	"fmt"
	consulApi "github.com/hashicorp/consul/api"
	"go-proxy/common"
	"go-proxy/config"
)

type ConsulService struct {
	consulClient *consulApi.Client
}

func NewConsulService() *ConsulService {
	return &ConsulService{}
}

func (c *ConsulService) InitService(service *config.Service) error {
	// 创建一个默认配置
	consulConfig := consulApi.DefaultConfig()
	consulConfig.Address = service.Consul.Address
	if len(service.Consul.Token) > 0 {
		consulConfig.Token = service.Consul.Token
	}
	if len(service.Consul.Scheme) > 0 {
		consulConfig.Scheme = service.Consul.Scheme
	}
	if len(service.Consul.Datacenter) > 0 {
		consulConfig.Datacenter = service.Consul.Datacenter
	}

	// 创建一个新的 Consul 客户端实例
	consulClient, err := consulApi.NewClient(consulConfig)
	if err != nil {
		common.LogErrorf("creating consul client error:%v", err)
		return err
	}

	self, err := consulClient.Agent().Self()
	common.LogDebugF("init consul client self:%v", self)
	if err != nil {
		common.LogErrorf("consul connect error:%v", err)
		return err
	}

	c.consulClient = consulClient
	return nil
}

func (c *ConsulService) GetInstances(service *config.Service, route *config.Route) ([]*InstanceInfo, error) {
	consulClient := c.consulClient
	catalog := consulClient.Catalog()
	catalogServices, _, err := catalog.Service(route.InstanceName, "", nil)
	common.LogDebugF("get consul catalogServices:%v", catalogServices)
	if err != nil {
		common.LogErrorf("get consul service=%s register=%s instances error:%v", service.Name, route.InstanceName, err)
		return nil, err
	}

	instances := make([]*InstanceInfo, 0)
	for _, instance := range catalogServices {
		instances = append(instances, &InstanceInfo{
			Address: fmt.Sprintf("http://%s:%d", instance.ServiceAddress, instance.ServicePort),
			Port:    uint64(instance.ServicePort),
			Host:    instance.ServiceAddress,
		})
	}
	common.LogDebugF("get consul instances:%v", catalogServices)
	return instances, nil
}
